package com.yanqu.road.server.command;

import com.yanqu.road.utils.classutil.ClassHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * 加载所有command
 */
public final class CommandControl {

    private static final Map<Integer, Class<?>> cmdPool = new HashMap<>();
    private static Logger logger = LogManager.getLogger(CommandControl.class.getName());

    public static Command getCommand(int code) {
        try {
            return (Command) cmdPool.get(code).newInstance();
        } catch (Exception e) {
            logger.error("get cmd {} error.", code, e);
            return null;
        }
    }

    private CommandControl() {
    }


    private static void analysisCommandClass(Class<?> data) {
        try {

            Cmd cmd = data.getAnnotation(Cmd.class);
            if (cmd == null) {
                return;
            }
            if (cmdPool.get(cmd.code()) != null) {
                logger.error("exist same cmd code : {},", cmd.code());
                return;
            }
            cmdPool.put(cmd.code(), data);
        } catch (Exception e) {
            logger.error("load cmd error : {} ", data.getName(), e);
        }
    }

    public static boolean loadCommand() {
        try {
            String packageName = "com.yanqu.road.server";
            Package pack = Package.getPackage(packageName);
            for (Class<?> data : ClassHelper.getClasses(pack)) {
                analysisCommandClass(data);
            }
            return true;
        } catch (Exception e) {
            logger.error("load cmd failure", e);
            return false;
        }
    }

    public static Map<Integer, Class<?>> getCmdPool() {
        return cmdPool;
    }
}
